package master

import (
	"fmt"
	"iec61850/model"
	"iec61850/protocol"
)

type Master struct {
	client *protocol.IEC61850Client
}

func NewMaster() *Master {
	return &Master{
		client: protocol.NewIEC61850Client(),
	}
}

func (m *Master) Connect(addr string) error {
	return m.client.Connect(addr)
}

func (m *Master) ReadAttributes() (map[string][]model.DeviceAttribute, error) {
	node, err := m.client.GetLogicalNode("MMXU1")
	if err != nil {
		return nil, err
	}

	attrs := make(map[string][]model.DeviceAttribute)
	for name, value := range node.GetDataObjects() {
		attrs["MMXU1"] = append(attrs["MMXU1"], model.DeviceAttribute{
			Name:  name,
			Value: value,
		})
	}

	return attrs, nil
}

func (m *Master) ExecuteOperation(operation string) error {
	// 使用IEC 61850协议执行操作
	xcbr1, err := m.client.GetLogicalNode("XCBR1")
	if err != nil {
		return err
	}

	switch operation {
	case "TurnOn":
		return xcbr1.SetDataObject("Pos", "on")
	case "TurnOff":
		return xcbr1.SetDataObject("Pos", "off")
	default:
		return fmt.Errorf("unsupported operation")
	}
}

// MeasurementReport sends a measurement report via MMS
func (m *Master) MeasurementReport(measurements map[string]float64) error {
	// Convert map[string]float64 to map[string]interface{}
	params := make(map[string]interface{})
	for k, v := range measurements {
		params[k] = v
	}

	msg := &protocol.IEC61850Message{
		Type: "MMSReport",
		Payload: protocol.MMSReportRequest{
			ReportType: "Measurement",
			Parameters: params,
		},
	}

	return m.sendMMSReport(msg)
}

func (m *Master) sendMMSReport(msg *protocol.IEC61850Message) error {
	if err := m.SendMessage(msg); err != nil {
		return fmt.Errorf("failed to send MMS report: %v", err)
	}

	resp, err := m.ReceiveMessage()
	if err != nil {
		return fmt.Errorf("failed to receive MMS report response: %v", err)
	}

	if resp.Type == "Error" {
		return fmt.Errorf("server error: %s", resp.Payload)
	}

	reportResp, ok := resp.Payload.(protocol.MMSReportResponse)
	if !ok || !reportResp.Success {
		return fmt.Errorf("MMS report failed")
	}

	return nil
}

func (m *Master) SendMessage(msg *protocol.IEC61850Message) error {
	return m.client.SendMessage(msg)
}

func (m *Master) ReceiveMessage() (*protocol.IEC61850Message, error) {
	return m.client.ReceiveMessage()
}
